-- 注册账号

local httparg               = require("shared.api.httparg")
local response              = require("shared.api.response")
local config                = require("config")
local tag                   = httparg.tag()
local assertion             = httparg.assertion
local httpclient            = require "shared.http.client"
local util                  = require "proxy.game.common.util"

local ngx                   = _G.ngx
local get_response_spec     = util.get_response_spec
local fill_response_header  = util.fill_response_header
local is_match_content_type = util.is_match_content_type
local get_content_decoder   = util.get_content_decoder
local get_method            = util.get_method

local cjson                 = require "cjson.safe"
      cjson.encode_max_depth(32)
      cjson.decode_max_depth(32)

local ACCESS_TOKEN_TTL = config.VAR.ACCESS_TOKEN_TTL


local ip = ngx.req.get_headers()['IP']
local ARGS = {
  tag.body('json', 'required'),

  username      = tag.json.username        ('string', 'required'),
  password      = tag.json.password        ('string', 'required'),
  mobile        = tag.json.mobile          ('string'),
  email         = tag.json.email           ('string'),
  birthdate     = tag.json.birthdate       ('string'),
  referencer    = tag.json.referencer      ('string'),
  ip            = ip,
  adjust        = tag.json.adjust          ('map'),
}


-- ngx.log(ngx.ERR, ip)
--調用nsq
local call_nsq=function()
    --nsq
    local producer = require "resty.nsq.producer"
    local NSQ= config._Event_Bus_Nsq

    local prod = producer:new()
   local ok, err = prod:connect(NSQ.host,NSQ.port)
   -- local ok, err = prod:connect("10.101.137.80",4150)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end
    local nsqMsg = {timestamp = ngx.time(),
                           ip =ip}
    local NSQ_MSG_BODY= cjson.encode(nsqMsg)
    ngx.log(ngx.ERR, NSQ_MSG_BODY)
    local  ok, err = prod:pub(GAAS_NSQ.register,NSQ_MSG_BODY )
    if not ok then
        ngx.say("failed to pub: ", err)
        return
    end
    ok, err = prod:close()
    if not ok then
        ngx.say("failed to close: ", err)
        return
    end

end

  local ADDRESS = config.ENV.DATAGATE_SERVICE
  local ACTION  = string.format("%s/account",ngx.var.oauth_brand)


  if not ADDRESS or not ACTION then
    ngx.status = ngx.HTTP_NOT_FOUND
    ngx.exit(ngx.OK)
  end

do
  local location = ngx.unescape_uri(ADDRESS..ACTION)
  local method   = "CREATE"
  local headers  = ngx.req.get_headers()
  ngx.req.read_body()

  ARGS.birthdate = os.date("%Y-%m-%d", ARGS.birthdate)
  local data     = cjson.encode(ARGS)
  local query    = ngx.var.args

--   do
--     headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
--   end


  local rmvLowKey = "x-http-method-override"
  local rmvKey2   = "accept-encoding"
  for k,v in pairs(headers) do
     local low=string.lower(k)
     if low==rmvLowKey  or low==rmvKey2   then
       headers[k]=nil
     end
  end

  headers['X-HTTP-Method-Override']=method

  local resp, err = httpclient.new()
    :uri(location)
    :headers(headers)
    :query(query)
    :body(data)
    :send(method, 2000, nil)

  if err or (not resp) then
    ngx.status = 500
    ngx.say(err)
    ngx.exit(ngx.OK)
  end


  ngx.header['Server']       = ngx.var.SERVICE_NAME
  ngx.header['Content-Type'] = resp.headers['Content-Type']
  ngx.status                 = resp.status
  rmvLowKey                  ="content-length"
  --如果我们修改了回应的内容，不是和调用的service返回的长度一样，"content-length"需要拿掉，不然回复出去的长度对不上
  for k,v in pairs(resp.headers) do
     local low =   string.lower(k)
     if    low ==  rmvLowKey then
      resp.headers[k]=nil
     end
  end
  fill_response_header(resp.headers)


  local replyInfo = resp.body
  local regRes    = cjson.decode(resp.body)
  if    regRes and regRes.account then
      replyInfo   = cjson.encode({timestamp=ngx.time()})
  else
      if resp.body then
         ngx.log(ngx.ERR,"dataService response err"..resp.body)
      else
         ngx.log(ngx.ERR,"dataService response err")
      end
  end

  --adjust
  do
    ngx.log(ngx.ERR, "adjust绑定-create1:", cjson.encode(regRes))
    ngx.log(ngx.ERR, "adjust绑定-create2:", cjson.encode(ARGS))
    if regRes and ARGS.adjust then
      ngx.log(ngx.ERR, "adjust绑定-create3:")
      local dataapi    = require("shared.api.dataapi")
      local adjustArgs = ARGS.adjust
      local reply, err = dataapi.adjust_device.create(
        {
          account     = regRes.account or "",
          adid        = adjustArgs.adid or "",
          adid_type   = adjustArgs.adid_type or "",
          app_id      = adjustArgs.app_id or "",
          device_info = adjustArgs.device_info or nil,
        })
      if err then
        ngx.log(ngx.ERR, "adjust绑定失败：", cjson.encode(err))
      end
    end
  end

  ngx.say(replyInfo)
  --call_nsq()
  ngx.exit(ngx.OK)
end

